//
//  AppController.m
//  wiSync
//
//  Created by Javier Segura Perez on 12/9/07.
//  Copyright 2007 iFrancis Development Team. All rights reserved.
//

#import "AppController.h"
#import "Script.h"
#import "Addon.h"

@implementation AppController

// App Events
- (void) awakeFromNib
{
	NSBundle	*bundle = [NSBundle mainBundle];
	NSString	*cmd = [NSString stringWithFormat:@"/bin/sh '%@/ipcheck.sh'", [bundle resourcePath]];
	Script		*script = [Script new];

	[macUserName setStringValue:NSUserName()];
	[macIP setStringValue:[script runCommand:cmd]];	
	[script release];
	
	NSUserDefaults	*defaults = [NSUserDefaults standardUserDefaults];
	NSArray			*keys = [NSArray arrayWithObjects:@"iPhoneSyncDir", @"MacSyncDir", @"isInstalled", nil];
	NSArray			*values = [NSArray arrayWithObjects:@"Sync", NSHomeDirectory(), @"NO", nil];
    NSDictionary	*appDefaults = [NSDictionary dictionaryWithObjects:keys forKeys:values];
    
	[defaults registerDefaults:appDefaults];

	[syncFolderiPhone setStringValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"iPhoneSyncDir"]];
	[syncFolder setStringValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"MacSyncDir"]];
	if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isInstalled"] == YES) 
		[installButton setTitle:@"ReInstall"];
}

- (void)applicationWillTerminate:(NSNotification *)aNotification
{
	[[NSUserDefaults standardUserDefaults] setObject:[syncFolder stringValue] forKey:@"MacSyncDir"];	
	[[NSUserDefaults standardUserDefaults] setObject:[syncFolderiPhone stringValue] forKey:@"iPhoneSyncDir"];
}

// Interface Builder Actions
- (IBAction)browse:(id)sender
{
	int			result;
	NSOpenPanel *oPanel = [NSOpenPanel openPanel];
		
	[oPanel setAllowsMultipleSelection:NO];
	[oPanel setCanChooseDirectories:YES];
	[oPanel setCanCreateDirectories:YES];
	
	result = [oPanel runModalForDirectory:NSHomeDirectory() file:nil];
	if (result == NSOKButton) [syncFolder setStringValue:[oPanel filename]];
}

- (IBAction)sync:(id)sender
{

	NSBundle		*bundle = [NSBundle mainBundle];
	NSMutableString	*cmd;
	NSMutableString	*enviroment;
	NSMutableString	*app;
	Script			*script = [Script new];

	// 0. We show the Sheet with the Progress Indicator
	[installProgress setUsesThreadedAnimation:YES];	
	[NSApp	beginSheet: sheetWindow
			modalForWindow: window
            modalDelegate: self
            didEndSelector: nil
            contextInfo: nil];
	NSModalSession session = [NSApp beginModalSessionForWindow:sheetWindow];

	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:0.0];
	[progressLabel setStringValue:@"Beginning Synchronization..."];
	[NSApp runModalSession:session];
	// 1a. syncnow.sh -> params ( iphone sync folder, mac sync dir, iphone ip and iphone root pass)
	app = [NSMutableString stringWithFormat:@"/bin/sh '%@/syncnow.sh'", [bundle resourcePath]];
	enviroment = [NSMutableString stringWithFormat:@"export istore=\"%@\"; export macdir=\"%@\"; export phoneip=%@; export rootpass_old=%@",
								[syncFolderiPhone stringValue],
								[syncFolder stringValue],
								[iPhoneIP stringValue],
								[oldiPhonePassword stringValue]];
	cmd = [NSMutableString stringWithFormat:@"%@; %@", enviroment, app];
	NSLog([script runCommand:cmd]);
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:35.0];
	[progressLabel setStringValue:@"Initializing..."];
	[NSApp runModalSession:session];
	
	// 2a. run_exp_rsync1.sh	
	cmd = [NSString stringWithFormat:@"/bin/sh '/Applications/wiSync/Resources/rScripts/run_exp_rsync1.sh'"];
	NSLog([script runCommand:cmd]);
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:75.0];
	[progressLabel setStringValue:@"Synchronizing Mac Files..."];
	[NSApp runModalSession:session];

	// 3a. run_exp_rsync2.sh	
	cmd = [NSString stringWithFormat:@"/bin/sh '/Applications/wiSync/Resources/rScripts/run_exp_rsync2.sh'"];
	NSLog([script runCommand:cmd]);	
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:100.0];
	[progressLabel setStringValue:@"Synchronizing iPhone Files..."];
	[NSApp runModalSession:session];

	/*[syncProgress displayIfNeeded];	
	[syncProgress stopAnimation:(id)sender];*/
		
	[script release];
	
	// Unloading sheet Progress and the modal session
	sleep(1); // I put this to view the 100% pogress
	[NSApp endModalSession:session];
	[sheetWindow orderOut:self];
	[NSApp endSheet:sheetWindow];
	[installProgress setDoubleValue:0.0];		
}

- (IBAction)remove:(id)sender
{

	NSBundle		*bundle = [NSBundle mainBundle];
	NSMutableString	*cmd;
	NSMutableString	*enviroment;
	NSMutableString	*app;
	Script			*script = [Script new];

	// 0. We show the Sheet with the Progress Indicator
	[installProgress setUsesThreadedAnimation:YES];	
	[NSApp	beginSheet: sheetWindow
			modalForWindow: window
            modalDelegate: self
            didEndSelector: nil
            contextInfo: nil];
	NSModalSession session = [NSApp beginModalSessionForWindow:sheetWindow];

	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:0.0];
	[progressLabel setStringValue:@"Beginning Uninstallation..."];
	[NSApp runModalSession:session];
	// 1a. remove.sh -> params ( iphone sync folder, mac sync dir, iphone ip and iphone root pass)
	app = [NSMutableString stringWithFormat:@"/bin/sh '%@/remove.sh'", [bundle resourcePath]];
	enviroment = [NSMutableString stringWithFormat:@"export rsrcpath=\"%@\"; export phoneip=%@; export rootpass_old=%@",
								[bundle resourcePath],
								[iPhoneIP stringValue],
								[oldiPhonePassword stringValue]];
	cmd = [NSMutableString stringWithFormat:@"%@; %@", enviroment, app];
	NSLog([script runCommand:cmd]);
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:35.0];
	[progressLabel setStringValue:@"Initializing..."];
	[NSApp runModalSession:session];
	
	// 2a. run_exp_ssh3.sh	
	cmd = [NSString stringWithFormat:@"/bin/sh '%@/run_exp_ssh3.sh'", [bundle resourcePath]];
	NSLog([script runCommand:cmd]);
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:75.0];
	[progressLabel setStringValue:@"Uninstalling..."];
	[NSApp runModalSession:session];
		
	[script release];
	
	// Unloading sheet Progress and the modal session
	sleep(1); // I put this to view the 100% pogress
	[NSApp endModalSession:session];
	[sheetWindow orderOut:self];
	[NSApp endSheet:sheetWindow];
	[installProgress setDoubleValue:0.0];	
	[installButton setTitle:@"Install"];	
	[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isInstalled"];	
}

- (IBAction)install:(id)sender
{	
	NSBundle		*bundle = [NSBundle mainBundle];
	NSMutableString	*cmd;
	NSMutableString	*enviroment;
	NSMutableString	*app;
	Script			*script = [Script new];
	
	//Checking...
	if ([[syncFolderiPhone stringValue] length] > 0)
		[syncFolderiPhone setStringValue:[Addon replaceCharacterInString:[syncFolderiPhone stringValue] search:' ' replace:'_']];
	else 
	{
		NSAlert *alert = [[[NSAlert alloc] init] autorelease];
		[alert addButtonWithTitle:@"OK"];
		[alert setMessageText:@"The iPhone Sync folder is empty."];
		[alert setInformativeText:@"You must to provide a valid sync folder for the iPhone"];
		[alert setAlertStyle:NSWarningAlertStyle];
		[alert beginSheetModalForWindow:window modalDelegate:self didEndSelector:nil contextInfo:nil];
		return;
	}
		
	// 0. We show the Sheet with the Progress Indicator
	[installProgress setUsesThreadedAnimation:YES];	
	[NSApp	beginSheet: sheetWindow
			modalForWindow: window
            modalDelegate: self
            didEndSelector: nil
            contextInfo: nil];
	NSModalSession session = [NSApp beginModalSessionForWindow:sheetWindow];
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:0.0];
	[NSApp runModalSession:session];
		
	// 1. create_rsync.sh -> params (iphone sync folder, local sync folder, username, local ip)
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:10.0];
	[progressLabel setStringValue:@"Beginning Installation..."];
	[NSApp runModalSession:session];
	
	app = [NSMutableString stringWithFormat:@"/bin/sh '%@/create_rsync.sh'", [bundle resourcePath]];
	enviroment = [NSMutableString stringWithFormat:@"export istore=\"%@\"; export macdir=\"%@\"; export macuser=%@; export ipaddr=%@",
								[syncFolderiPhone stringValue],
								[syncFolder stringValue],
								[macUserName stringValue],
								[macIP stringValue]];
	cmd = [NSMutableString stringWithFormat:@"%@; %@", enviroment, app];
	NSLog([script runCommand:cmd]);
	
	// 2. create_crontabs.sh -> params (interval time)	
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:15.0];
	[progressLabel setStringValue:@"Creating Scripts..."];
	[NSApp runModalSession:session];

	[app setString:[NSMutableString stringWithFormat:@"/bin/sh '%@/create_crontabs.sh'", [bundle resourcePath]]];
	[enviroment setString:[NSMutableString stringWithFormat:@"export sync_interval=%d; export sync_hour=%@", 
								[scheduleInterval selectedRow], 
								[scheduleHour stringValue]]];
	cmd = [NSMutableString stringWithFormat:@"%@; %@", enviroment, app];
	NSLog([script runCommand:cmd]);

	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:25.0];
	[NSApp runModalSession:session];

	// 3. create_exp.sh -> params (macuser, local ip address, Mode settings and native apps)
	[installProgress displayIfNeeded];	
	[installProgress setDoubleValue:45.0];
	[NSApp runModalSession:session];

	[app setString:[NSMutableString stringWithFormat:@"/bin/sh '%@/create_exp.sh'", [bundle resourcePath]]];
	[enviroment setString:[NSMutableString stringWithFormat:@"export macuser=%@; export istore=\"%@\"; export rsrcpath=\"%@\"; export ipaddr=%@; export phoneip=%@; export crontabt=%d; export nativeSwitcher=%d; export nativeFinder=%d; export rootpass_edit_yn=%d; export rootpass_edit_string=\"%@\"; export rootpass_old=%@",
								[macUserName stringValue],
								[syncFolderiPhone stringValue],
								[bundle resourcePath],
								[macIP stringValue],
								[iPhoneIP stringValue],
								[modePopup indexOfSelectedItem],
								[nativeSwitcher state],
								[nativeFinder state],
								[changeiPhonePassword state],
								[iPhonePassword stringValue],
								[oldiPhonePassword stringValue]]];
	cmd = [NSMutableString stringWithFormat:@"%@; %@", enviroment, app];
	NSLog([script runCommand:cmd]);
	
	// 4. run_exp_ssh.sh	
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:55.0];
	[progressLabel setStringValue:@"Generating SSH Keys..."];
	[NSApp runModalSession:session];
	
	cmd = [NSString stringWithFormat:@"/bin/sh '%@/run_exp_ssh.sh'", [bundle resourcePath]];
	NSLog([script runCommand:cmd]);

	// 5. run_exp_scp1.sh	
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:60.0];
	[progressLabel setStringValue:@"Sending Scripts..."];
	[NSApp runModalSession:session];
	
	cmd = [NSString stringWithFormat:@"/bin/sh '%@/run_exp_scp1.sh'", [bundle resourcePath]];
	NSLog([script runCommand:cmd]);

	// 6. run_exp_scp2.sh	
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:70.0];
	[NSApp runModalSession:session];
	
	cmd = [NSString stringWithFormat:@"/bin/sh '%@/run_exp_scp2.sh'", [bundle resourcePath]];
	NSLog([script runCommand:cmd]);
	
	// 7. run_exp_scp3.sh		
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:80.0];
	[NSApp runModalSession:session];
	
	cmd = [NSString stringWithFormat:@"/bin/sh '%@/run_exp_scp3.sh'", [bundle resourcePath]];
	NSLog([script runCommand:cmd]);

	// 8. run_exp_scp4.sh		
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:85.0];
	[NSApp runModalSession:session];
	
	cmd = [NSString stringWithFormat:@"/bin/sh '%@/run_exp_scp4.sh'", [bundle resourcePath]];
	NSLog([script runCommand:cmd]);

	// 9. run_exp_scp4.sh		
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:95.0];
	[progressLabel setStringValue:@"Finalizing..."];
	[NSApp runModalSession:session];
	
	cmd = [NSString stringWithFormat:@"/bin/sh '%@/run_exp_scp5.sh'", [bundle resourcePath]];
	NSLog([script runCommand:cmd]);

	// 10. run_exp_ssh2.sh
	cmd = [NSString stringWithFormat:@"/bin/sh '%@/run_exp_ssh2.sh'", [bundle resourcePath]];
	NSLog([script runCommand:cmd]);
		
	[installProgress displayIfNeeded];
	[installProgress setDoubleValue:100.0];
	[NSApp runModalSession:session];
	
	[script release];
	
	// Unloading sheet Progress and the modal session
	sleep(1); // I put this to view the 100% pogress
	[NSApp endModalSession:session];
	[sheetWindow orderOut:self];
	[NSApp endSheet:sheetWindow];
	[installProgress setDoubleValue:0.0];
	[installButton setTitle:@"ReInstall"];	
	[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isInstalled"];
}
@end
